package com.ls.lserp.modules.setting.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lserp.modules.sys.utils.DictUtils;
import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import com.ls.lserp.modules.sys.utils.UserUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ls.lserp.modules.common.entity.UploadFile;
import com.ls.lserp.modules.material.entity.InventoryRequest;
import com.ls.lserp.modules.material.service.InventoryRequestService;
import com.ls.lserp.modules.setting.entity.CompanyList;
import com.ls.lserp.modules.setting.entity.Ognization;
import com.ls.lserp.modules.setting.entity.Process;
import com.ls.lserp.modules.setting.entity.WarehouseShelves;
import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.setting.service.ProcessService;
import com.ls.lserp.modules.sys.entity.Dict;
import com.ls.lserp.modules.sys.entity.User;
import com.ls.lserp.modules.trade.entity.BookingOrders;

import freemarker.template.Configuration;
import groovy.util.ResourceException;

@Controller
@RequestMapping(value = "${adminPath}/produce/technology")
public class processController extends BaseController{
	
	@Autowired
	// 保存 编辑 删除 方法
	private ProcessService processService;

	@Autowired
	Configuration freemarkerConfiguration;
	// 画面区分
	private static final String IMAGE_FLG="fashionStyleCreate";
		
	@ModelAttribute
	public Process get(@RequestParam(required=false) String id) {
		
		// 判断id是否为空
		if (StringUtils.isNotBlank(id)){
			
			// 执行查询语句 查询基本信息
			return processService.get(Long.parseLong(id));
		}else{
			
			// 若为空，实例化
			return new Process();
		}
	}
	
	
	/**
	 * @Title: 画面跳转用
	 * @return url
	 */
	@RequiresPermissions("produce:technology:view")
	@RequestMapping(value = { "" })
	public String list(Model model) {
		// 画面跳转
		return "modules/setting/process";
	}
	
	/**
	 * @Title: 画面检索
	 * @Description: 查询页面
	 * @param process
	 * @param request
	 * @param response
	 * @return searchList
	 * @throws Exception
	 */
	@RequiresPermissions("produce:technology:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(Process process, HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "process");
		// 拼接字符串供分页使用
		StringBuilder searchParam = new StringBuilder();
		// 客户
		searchParam.append("&ognizationName=");
		searchParam.append(process.getOgnizationName());
		// 品牌
		searchParam.append("&brandName=");
		searchParam.append(process.getBrandName());		
		//工艺类别
		searchParam.append("&procategory=");
		searchParam.append(process.getProcategory());
		//款式类别
		searchParam.append("&category=");
		searchParam.append(process.getCategory());
		
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam);
		
		// 查询一览页面数据
		Page<Process> page = processService.findList(new Page<Process>(request, response),
				process);
		// 读取系统路径
		String strUri = request.getContextPath() + Global.getAdminPath();
		// 读取文件生成字符串
		String strHtml = "";
		Map<String, Object> map = new HashedMap();
		map.put("adminUri", strUri);
		map.put("processs", page.getList());
		map.put("pageNo", page.getPageNo());
		map.put("pageSize", page.getPageSize());
		strHtml = FreeMarkerTemplateUtils
				.processTemplateIntoString(freemarkerConfiguration.getTemplate("process.ftl"), map);
		listMap.put("process", strHtml);
		listMap.put("page", page.getHtml());

		// ajax返回结果
		return renderString(response, listMap);
	}
	
	
	
	/**
	 * 
	 * 功能：Java读取txt文件的内容 1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
	 * 3：读取到输入流后，需要读取生成字节流
	 * 
	 * @param filePath
	 * @return html
	 */
	public String readTxtFile(String filePath) {
		String strHtml = "";
		try {
			String encoding = "UTF-8";
			File file = new File(filePath);
			// 判断文件是否存在
			if (file.isFile()) {
				InputStreamReader read = new InputStreamReader(
						// 考虑到编码格式
						new FileInputStream(file), encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				String lingText = null;
				while ((lingText = bufferedReader.readLine()) != null) {
					strHtml += lingText;
				}
				read.close();
			} else {

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strHtml;
	}
	
	/**
	 * 创建窗口
	 * 
	 * @return
	 */
	@RequiresPermissions("produce:technology:view")
	@RequestMapping(value = "create")
	public String create(Process process, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		
		List<Process> processList = processService.findListProcess(process);
		process.setProcessList(processList);

		model.addAttribute("process", process);	
		return "modules/setting/processCreate";

	}
	
	/**
	 * @Title: 进入编辑页面
	 * @return url
	 */
	@RequiresPermissions("produce:technology:view")
	@RequestMapping(value = { "edit" })
	public String edit(Process process,HttpServletRequest request, HttpServletResponse response,Model model) {
				
		        //process = processService.findACompany(process);
				// 获取当前用户
				User curLoginUser = process.getCurrentUser();
				// 下拉列表客户名称取得		
				Ognization paramOgnization = new Ognization();
				//账户类型（1、平台账户；2、店铺账户；3、加工厂账户；4、供货商账户；5、客户；）
				paramOgnization.setOgnizationType(5L);
				paramOgnization.setCurrentUser(curLoginUser);
				process.setVenderList(processService.selVenderList(paramOgnization));
								
				List<Process> processList = processService.findListProcess(process);
				process.setProcessList(processList);
				
	    		// 将查询结果赋值mvc model层返回jsp页面
				 model.addAttribute("process", process);	
			
				// 返回页面地址
				return "modules/setting/processCreate";
	}
	
	
	
	/**
	 * @Title: 查看
	 * @return url
	 */
	@RequiresPermissions("produce:technology:view")
	@RequestMapping(value = { "show" })
	public String show(Process process,Model model, HttpServletRequest request, HttpServletResponse response) {
		
		List<Process> processList = processService.findListProcess(process);
		process.setProcessList(processList);
		
    	// 将查询结果赋值mvc model层返回jsp页面
    		 model.addAttribute("process", process);
    	// 返回页面地址
		return "modules/setting/processShow";
	}
	
	
    
	/**
	  * @Title: add
	  * @Description: 新建子项
	  * @param @param category
	  * @param @param redirectAttributes
	  * @param @param model
	  * @param @return
	  * @return String 
	  * @throws
	  */
	@RequiresPermissions("produce:technology:edit")
	@RequestMapping(value = "add")
	public String add(Process process, Model model) {
		model.addAttribute("user", UserUtils.getUser().getFirstName() + UserUtils.getUser().getLastName());
		if (process.getImageFlg()!=null) {
			process.setProcategory(ResourcesUtil.getConfig("process_category_Special"));
		}
		model.addAttribute("process", process);
		
		// 返回页面地址
		return "modules/setting/processAdd";
	}
	
	

	/**
	 * 保存工艺
	 * 
	 * @return
	 * @throws ParseException
	 * @throws ResourceException
	 * @throws  
	 */
	@RequiresPermissions("produce:technology:edit")
	@RequestMapping(value = "saveProcess")
	@ResponseBody
	public String saveProcess(Process process, HttpServletResponse response)throws ResourceException{
		        Map<Object, Object> listMap = new HashMap<Object, Object>();
				if (IMAGE_FLG.equals(process.getImageFlg())) {
					try {
						// 保存数据
						processService.saveProcess(process);
						listMap.put("proId",process.getId());
						listMap.put("saveFlg","true");
					} catch (Exception e) {
						listMap.put("saveFlg","false");
						logger.error (e.getMessage (), e);
					}
				} else {
					// 判断id是否为null （判断新建或修改）
					if(process.getId()!=null){
						// 编辑数据
						// 判断数据是否删除
						Process processNew = get(process.getId().toString());
						// 判断数据是否删除
						if(processNew==null || BaseEntity.DEL_FLAG_DELETE.equals(processNew.getDeleteFlag())){
							// 返回提示信息
							return renderString(response,AjaxDone.error(getText("process_edit_save_msg_fail")));
						}
						// 排他处理
						if(process.getVersion()==get(process.getId().toString()).getVersion()){

							// 版本号加1
							process.setVersion(process.getVersion()+1);
						}else{

							// 返回提示信息
							return renderString(response,AjaxDone.error(getText("process_edit_save_msg_fail")));
						}

					}
				
					// 保存数据				
					processService.saveProcess(process);
					listMap.put("saveFlg","true");
					listMap.put("processId", process.getId());
					// 保存成功返回提示信息
					return renderString(response, listMap);
				}
			// ajax返回结果
			return renderString(response,listMap);
	}
	
	 /**
		 * 进入状态信息页面
		 * @param process
		 * @param model
		 * @return
		 */
		@RequiresPermissions("produce:technology:view")
		@RequestMapping(value = "statusmessages")
		public String statusmessages(Process process, Model model) {
			 	
			// 执行查询方法查询子项数据为0的数据
	    	//List<Process> processListFind=processService.findList(process);
	    	// 执行查询方法查询子项数据
	    	//List<Process> processList= processService.findListProcess(process);
	    	process = processService.get(process);
	    	// 将查询结果赋值mvc model层返回jsp页面
	    	//model.addAttribute("processListFind", processListFind);
	    	// 将查询结果赋值mvc model层返回jsp页面
	    	//model.addAttribute("processList", processList);

	    	// 将查询结果赋值mvc model层返回jsp页面
	    	model.addAttribute("process", process);
	        
	        // 返回页面地址
	        return "modules/setting/processShowTwo";
		}
		
		 /**
		 * 进入状态信息页面
		 * @param process
		 * @param model
		 * @return
		 */
		@RequiresPermissions("produce:technology:view")
		@RequestMapping(value = "updateMessages")
		public String updateMessages(Process process, Model model) {
			model.addAttribute("user", UserUtils.getUser().getFirstName() + UserUtils.getUser().getLastName());
	    	//process = processService.get(process);
	    	// 将查询结果赋值mvc model层返回jsp页面
	    	model.addAttribute("process", process);
	        // 返回页面地址
	        return "modules/setting/processAdd";
		}
		
		/**
		 * 删除工艺
		 * 
		 * @return
		 * @throws ParseException
		 * @throws ResourceException
		 * @throws  
		 */
		@RequiresPermissions("produce:technology:edit")
		@RequestMapping(value = "deleteSave")
		@ResponseBody
		public String deleteSave(Process process, HttpServletResponse response)throws ResourceException{
			        Map<Object, Object> listMap = new HashMap<Object, Object>();
						try {
							// 保存数据
							process.preUpdate();
							processService.deleteProcess(process);
							listMap.put("saveFlg","true");
						} catch (Exception e) {
							listMap.put("saveFlg","false");
							logger.error (e.getMessage (), e);
						}
					
				// ajax返回结果
				return renderString(response,listMap);
		}
	

}
